package com.sky.config;

import com.sky.constant.RedisListenerConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Objects;

@Configuration
@Slf4j
public class RedisConfiguration {
    @Autowired
    private OrderMapper orderMapper;

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("开始创建redisTemplate对象...");
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory, MessageListenerAdapter messageListenerAdapter) {
        log.info("开始创建redisMessageListenerContainer对象...");
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(messageListenerAdapter, new PatternTopic(RedisListenerConstant.EXPIRED_EVENT_PATTERN));
        return container;
    }


    @Bean
    public MessageListenerAdapter messageListenerAdapter(){
        return new MessageListenerAdapter((MessageListener) (message, pattern) -> {
            log.info("redis监听到过期订单：{}",message.toString());
            String expiredKey = new String(message.getBody(), StandardCharsets.UTF_8);
            if (expiredKey.startsWith(RedisListenerConstant.UNPAID_EXPIRED_KEY)){
                Long orderId = Long.valueOf(expiredKey.substring(RedisListenerConstant.UNPAID_EXPIRED_KEY.length()));
                Orders order = orderMapper.getById(orderId);
                if (Objects.equals(order.getPayStatus(), Orders.PAID)){
                    log.info("订单{}已支付",orderId);
                    return;
                }
                log.info("订单{}支付超时，取消订单",orderId);
                Orders updateOrder = Orders.builder().id(orderId).status(Orders.CANCELLED).cancelReason("支付超时").cancelTime(LocalDateTime.now()).build();
                orderMapper.update(updateOrder);
            }
        });
    }

}
